<template>
  <transition name="el-zoom-in-center">
    <div class="cu-preview-main campus-form">
      <div class="cu-common-page-header">
        <el-page-header @back="goBack" :content="!dataForm.id ? '新建' : isDetail ? '详情' : '编辑'" />
        <div class="btns">
          <el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail">确 定</el-button>
          <el-button @click="goBack">取 消</el-button>
        </div>
      </div>
      <div class="main" v-loading="loading">
        <el-form ref="elForm" :model="dataForm" size="small" label-width="100px" label-position="right" :disabled="!!isDetail" :rules="rules">
          <el-col :span="24">
            <el-form-item label-width="0">
              <groupTitle content-position="left" content="基本信息"></groupTitle>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="8">
            <el-form-item label="校区品牌" prop="brand">
              <el-select v-model="dataForm.brand" placeholder="请选择签约品牌" @change="handleChangeBrand" filterable clearable
                required :style='{"width":"100%"}'>
                <el-option :key="item.id" :label="item.fullName" :value="item.enCode" v-for="item in brandOptions" />
              </el-select>
            </el-form-item>
          </el-col>-->
          <el-col :span="8">
            <el-form-item label="报名校区" prop="campusId">
              <el-select v-model="dataForm.campusId" placeholder="请选择" filterable clearable required :style="{ width: '100%' }">
                <el-option v-for="(item, index) in campusOptions" :key="index" :label="item.fullName" :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="支付金额" prop="payAmount">
              <el-input v-model="dataForm.payAmount" placeholder="请输入" clearable required :style="{ width: '100%' }"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <div></div>
          </el-col>
          <el-col :span="24">
            <el-form-item label="支付凭证" prop="payInfo">
              <custom-upload-img v-model="dataForm.payInfo" :fileSize="5" sizeUnit="MB" :limit="9"></custom-upload-img>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="订单备注" prop="memo">
              <el-input v-model="dataForm.memo" placeholder="请输入" show-word-limit :style="{ width: '100%' }" type="textarea" :autosize="{ minRows: 4, maxRows: 4 }"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="0">
              <groupTitle content-position="left" content="老师信息"></groupTitle>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label-width="0">
              <el-table :data="dataForm.teachers" size="mini" class="cu-common-table" empty-text="点击下方“添加老师”按钮可选择报名老师">
                <el-table-column prop="teacherId" label="老师编号" />
                <el-table-column prop="teacherName" label="老师姓名" />
                <el-table-column prop="gender" label="性别" align="center">
                  <template slot-scope="scope">
                    {{ scope.row.gender == 1 ? '男' : '女' }}
                  </template>
                </el-table-column>
                <el-table-column prop="mobile" label="手机号码" align="center" width="150" />
                <el-table-column prop="idCard" label="身份证号码" align="center" width="150" />
                <el-table-column prop="entryDate" label="入职时间" :formatter="custom.tableDateFormat" align="center" />
                <el-table-column prop="statusText" label="参训状态" align="center" width="80"></el-table-column>
                <el-table-column label="操作">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" class="cu-table-delBtn" @click="handleDelTrainOrderItemEntityList(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="table-actions" @click="openTeacherBox">
                <el-button type="text" icon="el-icon-plus">新增</el-button>
              </div>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <teacher-box :visible.sync="teacherBoxVisible" @closeForm="closeForm" :trainId="dataForm.trainId" :campusId="dataForm.campusId" ref="teacherBox" />
    </div>
  </transition>
</template>
<script>
import request from '@/utils/request'
import { getCampusSelector } from '@/api/campus/campus'
import { getTrainNoPagingList } from '@/api/campus/train'
import TeacherBox from './TeacherBox'
export default {
  components: { TeacherBox },
  props: [],
  data() {
    return {
      loading: false,
      visible: false,
      teacherBoxVisible: false,
      train: undefined,
      isDetail: false,
      dataForm: {
        // brand: undefined,
        orderCode: undefined,
        campusId: undefined,
        trainId: undefined,
        payInfo: [],
        memo: undefined,
        teachers: [],
        payMethod: undefined,
        payAmount: undefined,
        payTime: undefined,
        payStatus: undefined,
        createTime: undefined,
        createUserName: undefined,
        updateTime: undefined,
        updateUserName: undefined,
        source: '线下报名'
      },
      rules: {
        brand: [
          {
            required: true,
            message: '请选择校区品牌',
            trigger: 'change'
          }
        ],
        orderCode: [
          {
            required: true,
            message: '请输入订单编号',
            trigger: 'blur'
          }
        ],
        campusId: [
          {
            required: true,
            message: '请输入校区名称',
            trigger: 'blur'
          }
        ],
        trainId: [
          {
            required: true,
            message: '请输入报名师训',
            trigger: 'change'
          }
        ],
        payMethod: [
          {
            required: true,
            message: '请输入支付方式',
            trigger: 'change'
          }
        ],
        payAmount: [
          {
            required: true,
            message: '请输入支付金额',
            trigger: 'blur'
          },
          {
            pattern: /^\d+(\.\d{1,2})?$/,
            message: '请输入正确的金额',
            trigger: 'blur'
          }
        ],
        payTime: [
          {
            required: true,
            message: '请输入支付时间',
            trigger: 'change'
          }
        ],
        payStatus: [
          {
            required: true,
            message: '请输入支付状态',
            trigger: 'change'
          }
        ]
      },
      brandOptions: [],
      campusOptions: [],
      trainOptions: [],
      statusOptions: [],
      payMethodOptions: [],
      payStatusOptions: []
    }
  },
  computed: {},
  watch: {},
  created() {
    this.$store.dispatch('base/getDictionaryData', { sort: 'Brand' }).then(res => {
      this.brandOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'PaymentsType' }).then(res => {
      this.payMethodOptions = res
    })
    this.$store.dispatch('base/getDictionaryData', { sort: 'PayStatus' }).then(res => {
      this.payStatusOptions = res
    })
  },
  mounted() {
    getCampusSelector().then(res => {
      this.campusOptions = this.isDetail ? res.data : res.data.filter(i => (i.status == 'normal' || i.status == 'preparation' || i.status == 'expires') && (this.train.pushCampus == null || this.train.pushCampus.indexOf(i.provinceId) > -1))
      // this.campusOptions = res.data;
    })
    getTrainNoPagingList().then(res => {
      this.trainOptions = res.data
    })
  },
  methods: {
    goBack() {
      this.$emit('refresh')
    },
    init(id, isDetail) {
      this.dataForm.id = id || 0
      this.visible = true
      this.isDetail = isDetail || false
      this.$refs['elForm'].resetFields()
      this.$nextTick(() => {
        if (this.dataForm.id) {
          request({
            url: '/api/train/order/' + this.dataForm.id,
            method: 'get'
          }).then(res => {
            this.dataForm = res.data
            if (!this.dataForm.payInfo) this.dataForm.payInfo = []
          })
        }
      })
    },
    sign(row) {
      this.dataForm.trainId = row.id
      this.visible = true
      this.train = row
    },
    handleChangeBrand(val) {
      getCampusSelector({ brand: val }).then(res => {
        this.campusOptions = res.data.filter(i => i.status == 'normal')
      })
    },
    dataFormSubmit() {
      this.$refs['elForm'].validate(valid => {
        if (valid) {
          request({
            url: `api/train/order/offline`,
            method: 'post',
            data: this.dataForm
          }).then(res => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.visible = false
                this.$emit('refresh')
              }
            })
          })
        }
      })
    },
    // handleCampusChangeCampus (item) {
    //   getCampusTeacherList(this.dataForm.campusId).then((res) => {
    //     this.dataForm.teachers = res.data
    //   })
    // },
    openTeacherBox() {
      if (!this.dataForm.campusId) {
        this.$message({
          message: '请先选择报名校区',
          type: 'error',
          duration: 1000
        })
        return
      } else if (!this.dataForm.campusId) {
        this.$message({
          message: '请先选择报名师训',
          type: 'error',
          duration: 1000
        })
        return
      } else {
        this.teacherBoxVisible = true
        this.$nextTick(() => {
          this.$refs.teacherBox.initData(this.dataForm.teachers)
        })
      }
    },
    async closeForm(data) {
      if (data.length > 0) {
        this.dataForm.memo = data
          .map(o => {
            return o.teacherName
          })
          .toString()
        this.dataForm.teachers = data
        this.dataForm.orderAmount = this.train.price * data.length
      } else {
        this.$message({
          message: '请确认添加老师，否则订单不能创建',
          type: 'warning'
        })
      }
    },
    handleDelTrainOrderItemEntityList(index) {
      this.dataForm.teachers.splice(index, 1)
      this.dataForm.memo = this.dataForm.teachers
        .map(o => {
          return o.teacherName
        })
        .toString()
    }
  }
}
</script>
